package com.aluka.nirvana.framework.datasource.dynamic;

import com.aluka.nirvana.framework.datasource.annotation.TargetDataSource;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;

/**
 * 切换数据源advice
 * @author gongli
 *
 */
@Aspect
@Slf4j
public class DynamicDataSourceAspect {

	@Before("@annotation(ds)")
	public void changeDataSource(JoinPoint point , TargetDataSource ds) {
		String dsId = ds.value();
		if(!DynamicDataSourceContextHolder.containsDataSource(dsId)) {
			log.error(">>Nirvana<< 数据源[{}]不存在，使用默认数据源 > {}",dsId, DynamicDataSourceContextHolder.DEFAULT);
		}else {
			log.debug(">>Nirvana<< [{}] 使用数据源 : {}",point.getSignature().getName(),dsId);
			DynamicDataSourceContextHolder.setDataSourceType(dsId);
		}
	}
	
	@After("@annotation(ds)")
	public void restoreDataSource(JoinPoint point , TargetDataSource ds) {
		log.debug(">>Nirvana<< [{}]恢复到默认数据源 : {}",point.getSignature().getName(), DynamicDataSourceContextHolder.DEFAULT);
		DynamicDataSourceContextHolder.clearDataSourceType();
	}
}
